import Taro from '@tarojs/taro'
import { useState, useCallback, useEffect } from 'react'
import { UserPanel } from '@/types/global'
import { useGlobalWebSocket } from './useGlobalWebSocket'

interface RoomResource {
  status: string
  playerIps: string[]
  playerPanels: Record<string, UserPanel>
  blackBag: any[]
  cardListA: any[]
  cardListB: any[]
  cardListC: any[]
  cardListD: any[]
  gemPositon: string[]
  gemSource: any[]
  currentPlayerIp: string
  nextPlayerIp: string
  isFilled: boolean
  round: number
  keepCards: Record<string, any[]>
  buyCards: Record<string, any[]>
  gameConfig: any
  publicPrivilege: number
  canUsePrivilege: boolean
  canRefillGemBoard: boolean
  canPerformMainAction: boolean
}

interface UseRoomServiceProps {
  roomId: string; // 接收外部传入的roomId
  onRoomResourceUpdate?: (resource: RoomResource) => void
  onRoomCommand?: (command: any) => void
}

export const useRoomService = (props: UseRoomServiceProps) => {
  const { roomId, onRoomResourceUpdate, onRoomCommand } = props || {}
  
  // 使用全局 WebSocket 管理
  const globalWebSocket = useGlobalWebSocket()
  
  const [connectionStatus, setConnectionStatus] = useState<string>(globalWebSocket.connectionStatus)
  const [roomResource, setRoomResource] = useState<RoomResource | null>(globalWebSocket.roomResource)
  const [userIp, setUserIp] = useState<string>(globalWebSocket.userIp)
  const [isConnected, setIsConnected] = useState<boolean>(globalWebSocket.isConnected)

  // 同步全局状态
  useEffect(() => {
    setConnectionStatus(globalWebSocket.connectionStatus)
    setRoomResource(globalWebSocket.roomResource)
    setUserIp(globalWebSocket.userIp)
    setIsConnected(globalWebSocket.isConnected)
  }, [globalWebSocket.connectionStatus, globalWebSocket.roomResource, globalWebSocket.userIp, globalWebSocket.isConnected])

  // 注册回调函数以监听全局状态变化
  useEffect(() => {
    const unsubscribeResource = globalWebSocket.registerCallback('onRoomResourceUpdate', (resource: RoomResource) => {
      setRoomResource(resource)
      onRoomResourceUpdate?.(resource)
    })

    const unsubscribeCommand = globalWebSocket.registerCallback('onRoomCommand', (command: any) => {
      onRoomCommand?.(command)
    })

    const unsubscribeStatus = globalWebSocket.registerCallback('onConnectionStatusChange', (status: string) => {
      setConnectionStatus(status)
      setIsConnected(status === '已连接')
    })

    return () => {
      unsubscribeResource()
      unsubscribeCommand()
      unsubscribeStatus()
    }
  }, [onRoomResourceUpdate, onRoomCommand])

  // 发送指令到服务器
  const sendCommand = useCallback((destination: string, body: any): void => {
    globalWebSocket.sendCommand(destination, body)
  }, [globalWebSocket])

  // 加入房间
  const joinRoom = useCallback((targetRoomId?: string) => {
    const targetId = targetRoomId || roomId
    return globalWebSocket.joinRoom(targetId)
  }, [globalWebSocket, roomId])

  // 离开房间
  const leaveRoom = useCallback((): void => {
    sendCommand('/app/leave_room', {})
  }, [sendCommand])

  // 发送游戏指令
  const sendGameCommand = useCallback((command: string, payload: any = {}): void => {
    globalWebSocket.sendGameCommand(command, payload, roomId)
  }, [globalWebSocket, roomId, sendCommand])

  // 具体游戏指令方法
  const buyCard = useCallback((playerIp: string, cardId: string): void => {
    sendGameCommand('buy_card', { playerIp, cardId })
  }, [sendGameCommand])
  
  const buyCardWithGems = useCallback((playerIp: string, cardId: string, gemIds:string[]): void => {
    sendGameCommand('buy_card_with_gems', { playerIp, cardId, gemIds })
  }, [sendGameCommand])
  
  const reserveCard = useCallback((playerIp: string, cardId: string , goldGemPosition: number): void => {
    sendGameCommand('reserve_card', { playerIp, cardId, goldGemPosition })
  }, [sendGameCommand])

  const passTurn = useCallback((): void => {
    sendGameCommand('pass_turn', {})
  }, [sendGameCommand])

  const startGame = useCallback((): void => {
    sendGameCommand('start_game', {})
  }, [sendGameCommand])

  const usePrivilege = useCallback((playerIp: string, gemPositionIndex: number): void => {
    sendGameCommand('use_privilege', { playerIp, gemPositionIndex })
  }, [sendGameCommand])

  const gainPrivilege = useCallback((playerIp: string): void => {
    sendGameCommand('gain_privilege', { playerIp })
  }, [sendGameCommand])

  const takeGems = useCallback((playerIp: string, gemPositionIndices: number[]): void => {
    sendGameCommand('take_gems', { playerIp, gemPositionIndices })
  }, [sendGameCommand])

  const playAnotherRound = useCallback((): void => {
    sendGameCommand('play_another_round', {})
  }, [sendGameCommand])

  const changeCardColor = useCallback((playerIp: string, cardId: string, color: string): void => {
    sendGameCommand('change_card_color', { playerIp, cardId, color })
  }, [sendGameCommand])

  const takeGemFromOpponent = useCallback((playerIp: string, targetPlayerIp: string, gemColor: string): void => {
    sendGameCommand('take_gem_from_opponent', { playerIp, targetPlayerIp, gemColor })
  }, [sendGameCommand])

  const refillGemBoard = useCallback((playerIp: string ): void => {
    sendGameCommand('refill_gem_board', { playerIp })
  }, [sendGameCommand])

  const playerReady = useCallback((playerIp: string): void => {
    globalWebSocket.playerReady(playerIp, roomId)
  }, [globalWebSocket, roomId])

  // 创建房间
  const createRoom = useCallback(async () => {
    try {
      const response = await Taro.request({
        url: 'https://www.gemduel.xin/room/create',
        method: 'POST',
        header: { 'Content-Type': 'application/json' }
      })

      if (response.data.success) {
        Taro.showToast({ title: '房间创建成功', icon: 'success' })
        return { success: true, roomId: response.data.roomId }
      } else {
        Taro.showToast({ title: '创建失败', icon: 'none' })
        return { success: false, error: '创建失败' }
      }
    } catch (error) {
      console.error('创建房间失败:', error)
      Taro.showToast({ title: '请求失败', icon: 'none' })
      return { success: false, error: '请求失败' }
    }
  }, [])

  // 连接 WebSocket
  const connectWebSocket = useCallback((targetRoomId?: string) => {
    const targetId = targetRoomId || roomId
    return globalWebSocket.connectWebSocket(targetId)
  }, [globalWebSocket, roomId])

  // 断开连接
  const disconnectWebSocket = useCallback(() => {
    globalWebSocket.disconnectWebSocket()
  }, [globalWebSocket])

  // 获取房间资源（HTTP）
  const getRoomResource = useCallback(async (targetRoomId?: string) => {
    const targetId = targetRoomId || roomId
    return globalWebSocket.getRoomResource(targetId)
  }, [globalWebSocket, roomId])

  // 添加玩家（HTTP）
  const addPlayerToRoom = useCallback(async ( targetRoomId?: string) => {
    const targetId = targetRoomId || roomId
    const result = await globalWebSocket.addPlayerToRoom(targetId)
    if (result.success) {
      setUserIp(result.userIp)
    }
    return result
  }, [globalWebSocket, roomId])

  // 清理函数
  const cleanup = useCallback(() => {
    globalWebSocket.cleanup()
  }, [globalWebSocket])

  return {
    // 状态
    connectionStatus,
    roomResource,
    isConnected,
    userIp,
    
    // 基础方法
    createRoom,
    connectWebSocket,
    joinRoom,
    leaveRoom,
    sendGameCommand,
    disconnectWebSocket,
    getRoomResource,
    addPlayerToRoom,
    cleanup,
    
    // 具体游戏指令方法
    buyCard,
    buyCardWithGems,
    reserveCard,
    passTurn,
    startGame,
    usePrivilege,
    gainPrivilege,
    takeGems,
    playAnotherRound,
    changeCardColor,
    takeGemFromOpponent,
    refillGemBoard,
    playerReady,
    
    // 全局 WebSocket 引用
    globalWebSocket
  }
}